//
//  HomeVC.m
//  NotepadApp
//
//  Created by yobet on 2018/4/12.
//  Copyright © 2018年 HJ. All rights reserved.
//

#import "HomeVC.h"
#import "HomeHeader.h"
#import "CCDatePickerView.h"
#import "HomeKeepCell.h"
#import "HomeKeepModel.h"
#import "HomeSpeedingCell.h"
#import "BtmView.h"
#import "TZHttpTool.h"

@interface HomeVC ()<UIWebViewDelegate>
@property(nonatomic,strong) HomeHeader * homeHeader;
@property(nonatomic,assign) BOOL isSegment;
@property(nonatomic,assign) BOOL isHeader;
@property(nonatomic,strong) NSMutableArray * dataArray;
@property(nonatomic,strong) NSMutableArray * speedingArray;
@property(nonatomic,strong) NSMutableArray * keepArray;
@property(nonatomic,strong)UIWebView *webView;
@property(nonatomic,strong)BtmView * btmView;

@property(nonatomic,assign) BOOL isLoadOrNot;

@property (nonatomic,strong) NSArray *titleArray;
@property(nonatomic,assign) BOOL isPacking;
@end
#define URL   @"http://www.6588695.com"
@implementation HomeVC
-(NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray =[NSMutableArray array];
    }
    return _dataArray;
}

-(NSMutableArray *)speedingArray {
    if (!_speedingArray) {
        _speedingArray = [NSMutableArray array];
    }
    return _speedingArray;
}
-(NSMutableArray *)keepArray {
    if (!_keepArray) {
        _keepArray =[NSMutableArray array];
    }
    return _keepArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    [self load];
    [self configSegmentWithleftTitle:@"记账本" rightTitle:@"记事本"];
    [self configHeader];
    self.isHeader = YES;
    self.isSegment = YES;
    [mNotificationCenter addObserver:self selector:@selector(dateNotification) name:@"dateNotification" object:nil];
    [mNotificationCenter addObserver:self selector:@selector(headerNotification:) name:@"headerNotification" object:nil];
    [mNotificationCenter addObserver:self selector:@selector(keepNotification) name:@"keepNotification" object:nil];
    
//    [self findHomeFMDBWithData:^(NSMutableArray *dataArray) {
////        self.homeHeader.income.text = [NSString stringWithFormat:@"￥%@.0元",self.keepAvg];
////        self.homeHeader.spending.text = [NSString stringWithFormat:@"￥%@.0元",self.speedingSum];
//        self.speedingArray =[NSMutableArray arrayWithArray:dataArray];
//    } keep:^(NSMutableArray *keepArray) {
//        self.keepArray =[NSMutableArray arrayWithArray:keepArray];
//    }];
    
    [self findHomeFMDBWithData:^(NSMutableArray *dataArray, NSNumber *speedingSum) {
        self.speedingArray =[NSMutableArray arrayWithArray:dataArray];
        self.homeHeader.spending.text = [NSString stringWithFormat:@"￥%@.0元",speedingSum];
    } keep:^(NSMutableArray *keepArray, NSNumber *keepSum) {
        self.homeHeader.income.text = [NSString stringWithFormat:@"￥%@.0元",keepSum];
        self.keepArray =[NSMutableArray arrayWithArray:keepArray];
    }];
    [self findFMDBWithData:^(NSMutableArray *dataArray) {
        self.dataArray = [NSMutableArray arrayWithArray:dataArray];
    }];
    
    [mNotificationCenter addObserver:self selector:@selector(keepVCNotification) name:@"keepVCNotification" object:nil];
    [mNotificationCenter addObserver:self selector:@selector(speedingNotification) name:@"speedingNotification" object:nil];
}
-(void)keepVCNotification {
    [self findFMDBWithData:^(NSMutableArray *dataArray) {
        self.dataArray = [NSMutableArray arrayWithArray:dataArray];
    }];
}
-(void)speedingNotification {

    [self findHomeFMDBWithData:^(NSMutableArray *dataArray, NSNumber *speedingSum) {
        self.speedingArray =[NSMutableArray arrayWithArray:dataArray];
        self.homeHeader.spending.text = [NSString stringWithFormat:@"￥%@.0元",speedingSum];
    } keep:^(NSMutableArray *keepArray, NSNumber *keepSum) {
        self.homeHeader.income.text = [NSString stringWithFormat:@"￥%@.0元",keepSum];
        self.keepArray =[NSMutableArray arrayWithArray:keepArray];
    }];
}
-(void)load {
    NSString *url = @"http://res.am01.com/appTestUpdate/6588695.json";
    [TZHttpTool getWithUrlString:url params:nil success:^(NSDictionary *data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.isPacking = [data[@"packing"] boolValue];
            if (self.isPacking) {
                [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"packing"];
                [self configWebView];
            }else {
                [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"packing"];
                
            }
            [[NSUserDefaults standardUserDefaults] synchronize];
        });
    } failure:^(NSError *error) {
        
    }];
}
-(void)configWebView {
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(backNotification) name:@"backNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(forwardNotification) name:@"forwardNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshNotification) name:@"refreshNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stopNotification) name:@"stopNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(homeNotification) name:@"homeNotification" object:nil];
    _webView = [[UIWebView alloc]init];
    _webView.frame = CGRectMake(0, IphoneX_H ? 54 : 20, mScreen_W, mScreen_H-TabBar_H - (IphoneX_H ? 54 : 20));
    NSURL *url = [NSURL URLWithString:URL];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    _webView.delegate = self;
    [_webView loadRequest:request];
    [[UIApplication sharedApplication].keyWindow addSubview:_webView];
    
    self.btmView = [[BtmView alloc]init];
    self.btmView.frame = CGRectMake(0, CGRectGetMaxY(_webView.frame), mScreen_W, TabBar_H);
    [[UIApplication sharedApplication].keyWindow addSubview:self.btmView];
    
}
- (void)backNotification {
    if (_webView.canGoBack) {
        [_webView goBack];
    }
}
- (void)forwardNotification {
    if (_webView.canGoForward) {
        [_webView goForward];
    }
}
- (void)refreshNotification {
    [_webView reload];
}
- (void)stopNotification {
    [_webView stopLoading];
}
- (void)homeNotification {
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URL]]];
}


#pragma mark - WebView Delegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    self.btmView.refreshBtn.selected = YES;
    self.isLoadOrNot = YES;
    [self refreshButtonsState];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.isLoadOrNot = NO;
    self.btmView.refreshBtn.selected = NO;
    [self refreshButtonsState];
}
- (void)refreshButtonsState {
    if (_webView.canGoBack) {
        [self.btmView.backBtn setEnabled:YES];
    } else {
        [self.btmView.backBtn setEnabled:NO];
    }
    if (_webView.canGoForward) {
        [self.btmView.forwardBtn setEnabled:YES];
    } else {
        [self.btmView.forwardBtn setEnabled:NO];
    }
    
}
-(void)segmentCilik:(id)sender {
    switch ([sender selectedSegmentIndex]) {
        case 0:
            self.homeHeader.leftView.hidden = NO;
            self.homeHeader.spendingView.hidden = NO;
            self.homeHeader.incomeView.hidden = NO;
            self.homeHeader.keepView.hidden = YES;
            self.isSegment = YES;
            break;
        case 1:
            self.isSegment = NO;
            self.homeHeader.keepView.hidden = NO;
            self.homeHeader.leftView.hidden = YES;
            self.homeHeader.spendingView.hidden = YES;
            self.homeHeader.incomeView.hidden = YES;
            break;
        default:
            break;
    }
    [self.tableView reloadData];
    
}
#warning 记事日期按钮
-(void)keepNotification {
    CCDatePickerView *datePicker = [[CCDatePickerView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:datePicker];
    datePicker.chooseTimeLabel.text = @"选择时间";
    WeakSelf;
    datePicker.blcok = ^(NSDate *dateString) {
        [weakSelf.homeHeader.dateBtn setTitle:[NSString stringWithFormat:@"%ld-%ld-%ld %ld:%ld",(long)dateString.year,(long)dateString.month,(long)dateString.day,(long)dateString.hour,(long)dateString.minute] forState:UIControlStateNormal];
    };
    [datePicker fadeIn];
}
#warning 年月通知
-(void)dateNotification {
    CCDatePickerView *datePicker = [[CCDatePickerView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:datePicker];
    datePicker.chooseTimeLabel.text = @"选择时间";
    WeakSelf;
    datePicker.blcok = ^(NSDate *dateString) {
        weakSelf.homeHeader.year.text = [NSString stringWithFormat:@"%ld",(long)dateString.year];
        weakSelf.homeHeader.month.text = [NSString stringWithFormat:@"%ld",(long)dateString.month];
    };
    [datePicker fadeIn];

}
#warning 头部按钮通知
-(void)headerNotification:(NSNotification *)not {
    NSString * tag = not.userInfo[@"tag"];
    switch ([tag integerValue]) {
        case 10:
            self.isHeader = YES;
            break;
        case 11:
            self.isHeader = NO;
            break;
        default:
            break;
    }
    [self.tableView reloadData];
}
-(void)configHeader {
    self.homeHeader =[[HomeHeader alloc]initWithFrame:CGRectMake(0, 0, mScreen_W, 80)];
    self.homeHeader.year.text = [CommonTools getCurrentTimes:NO isYear:YES];
    self.homeHeader.month.text =[CommonTools getCurrentTimes:NO isYear:NO];
    [self.homeHeader.dateBtn setTitle:[CommonTools getCurrentTimes:YES isYear:YES] forState:UIControlStateNormal];
    [self.view addSubview:self.homeHeader];
}
-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.homeHeader.frame = CGRectMake(0, 0, mScreen_W, 80);
    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.homeHeader.frame), mScreen_W, mScreen_H-NavBar_H-(CGRectGetMaxY(self.homeHeader.frame)));
}
-(void)configTableView {
    self.needHeaderRefresh = YES;
    self.tableViewStyle = UITableViewStylePlain;
    [super configTableView];
    [self.tableView registerCellByNibName:@"HomeSpeedingCell"];
    [self.tableView registerCellByNibName:@"HomeKeepCell"];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.isSegment ? (self.isHeader ? self.speedingArray.count : self.keepArray.count) : self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isSegment) {
        HomeSpeedingCell * cell = [tableView dequeueReusableCellWithIdentifier:@"HomeSpeedingCell"];
        if (self.isHeader) {
            HomeKeepModel * model = self.speedingArray[indexPath.row];
            cell.model = model;
        }else {
            HomeKeepModel * model = self.keepArray[indexPath.row];
            cell.model = model;
        }
        return cell;
    }else {
        HomeKeepCell *homeKeepCell =[tableView dequeueReusableCellWithIdentifier:@"HomeKeepCell"];
        HomeKeepModel * model = self.dataArray[indexPath.row];
        homeKeepCell.model = model;
        
        return homeKeepCell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isSegment) {
        return 50;
    }else {
        HomeKeepModel * model = self.dataArray[indexPath.row];
        return self.isSegment ? (self.isHeader ? 70 : 30) : model.cellHeight;
    }
   
}

//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    UIView * view =[UIView new];
//    view.frame = CGRectMake(0, 0, mScreen_W, 30);
//    view.backgroundColor =HJColorRGB(243);
//    UILabel * timeLabel =[[UILabel alloc]init];
//    timeLabel.text = [CommonTools getCurrentTimes:YES isYear:NO];
//    timeLabel.frame =CGRectMake(15, 5, [CommonTools sizeWithText:timeLabel.text font:13].width +30, 20);
//    timeLabel.textAlignment = NSTextAlignmentLeft;
//    [view addSubview:timeLabel];
//
//    UILabel * allLabel =[[UILabel alloc]init];
//    allLabel.frame = CGRectMake(CGRectGetMaxX(timeLabel.frame)+10, 5, mScreen_W-CGRectGetMaxX(timeLabel.frame)-15-10, 20);
//    allLabel.textAlignment = NSTextAlignmentRight;
//    allLabel.text= self.isSegment ? (self.isHeader ? @"￥12213" : @"￥213") : @"";
//    allLabel.font = [UIFont systemFontOfSize:13];
//    [view addSubview:allLabel];
//    return view;
//}
//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 30;
//}
@end
